#include "src/net/http/http_response.h"

#include <format>

#include "src/net/buffer.h"

namespace fio66::net {
HttpResponse::HttpResponse(bool close) : close_connection_(close) {}

void HttpResponse::SetStatusCode(HttpStatusCode code) { status_code_ = code; }

void HttpResponse::SetStatusMessage(std::string_view message) {
  status_message_ = message;
}

void HttpResponse::SetContentType(std::string_view content_type) {
  AddHeader("Content-Type", std::string(content_type));
}

void HttpResponse::SetCloseConnection(bool on) { close_connection_ = on; }

bool HttpResponse::CloseConnection() const { return close_connection_; }

void HttpResponse::AddHeader(std::string_view key, std::string_view value) {
  headers_[std::string(key)] = std::string(value);
}

void HttpResponse::SetBody(std::string_view body) { body_ = body; }

void HttpResponse::AppendToBuffer(Buffer* out) const {
  out->Append(std::format("HTTP/1.1 {} ", static_cast<int32_t>(status_code_)));
  out->Append(status_message_);
  out->Append("\r\n");

  if (close_connection_) {
    out->Append("Connection: close\r\n");
  } else {
    out->Append(std::format("Content-Length: {}\r\n", body_.size()));
    out->Append("Connection: Keep-Alive\r\n");
  }

  for (const auto& header : headers_) {
    out->Append(header.first);
    out->Append(": ");
    out->Append(header.second);
    out->Append("\r\n");
  }

  out->Append("\r\n");
  out->Append(body_);
}

}  // namespace fio66::net
